<template>
    <div class="container">
        <!-- 搜索栏 -->
        <div class="search-container">
            <template v-if="!isDetail">
                <input type="text" placeholder="跟单编号" v-model="searchParams.ProcessGId" class="search-input" />
                <input type="text" placeholder="生产编号" v-model="searchParams.ProcessSid" class="search-input" />
                <input type="text" placeholder="物料编码" v-model="searchParams.ProcessBId" class="search-input" />
                <input type="text" placeholder="物料名称" v-model="searchParams.ProcessWname" class="search-input" />
            </template>
            <template v-else>
                <input type="text" placeholder="单据编码" v-model="searchParams.ProcessId" class="search-input" />
                <select v-model="searchParams.ProcessState" class="search-select">
                    <option value="">全部状态</option>
                    <option value="审核">已审核</option>
                    <option value="待审核">未审核</option>
                </select>
                <select v-model="searchParams.Processtype" class="search-select">
                    <option value="">业务类型</option>
                    <option value="装配车间">装配车间</option>
                    <option value="加工车间">加工车间</option>
                </select>
            </template>
            <div class="date-range">
                <input type="date" v-model="searchParams.KTime" class="search-input" />
                <span>至</span>
                <input type="date" v-model="searchParams.JTime" class="search-input" />
            </div>
            <button @click="handleSearch" class="search-button">搜索</button>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button class="btn btn-primary" @click="toggleDetail">
                {{ isDetail ? '单据' : '明细' }}
            </button>
            <button class="btn btn-success" @click="hoshow">新建</button>
            <button class="btn btn-warning" @click="handleExport">导出{{ isDetail ? '单据' : '生产' }}数据</button>
            <template v-if="isDetail">
                <button class="btn btn-danger" @click="handleDelete">删除</button>
                <button class="btn btn-info" @click="handleApprove">审核</button>
                <button class="btn btn-secondary" @click="handleReject">反审核</button>
            </template>
        </div>

        <!-- 明细表格 -->
        <template v-if="!isDetail">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>措施编号</th>
                        <th>措施编码</th>
                        <th>单批状态</th>
                        <th>生产编号</th>
                        <th>物料名称</th>
                        <th>物料编码</th>
                        <th>主计量</th>
                        <th>生产项</th>
                        <th>工序</th>
                        <th>施工数量</th>
                        <th>质量</th>
                        <th>工人</th>
                        <th>单位日期</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in tableData" :key="item.processId">
                        <td>{{ index + 1 }}</td>
                        <td>{{ item.measure_number }}</td>
                        <td>{{ item.measure_code }}</td>
                        <td>{{ item.batch_status }}</td>
                        <td>{{ item.production_number }}</td>
                        <td>{{ item.material_name }}</td>
                        <td>{{ item.material_code }}</td>
                        <td>{{ item.main_unit }}</td>
                        <td>{{ item.production_item }}</td>
                        <td>{{ item.process }}</td>
                        <td>{{ item.construction_qty }}</td>
                        <td>{{ item.quality }}</td>
                        <td>{{ item.workers }}</td>
                        <td>{{ formatDate(item.unit_date) }}</td>
                    </tr>
                </tbody>
            </table>
        </template>

        <!-- 单据表格 -->
        <template v-else>
            <table class="data-table">
                <thead>
                    <tr>
                        <th><input type="checkbox" v-model="isAllChecked" @change="handleAllCheck"></th>
                        <th>单据编码</th>
                        <th>单据日期</th>
                        <th>单据状态</th>
                        <th>业务类型</th>
                        <th>业务状态</th>
                        <th>审核日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in detailTableData" :key="item.processId">
                        <td><input type="checkbox" v-model="item.isChecked" @change="handleSingleCheck(item)"></td>
                        <td>{{ item.production_Material_Id }}</td>
                        <td>{{ formatDate(item.production_Material_DocumentDate) }}</td>
                        <td>{{ item.production_Material_Status }}</td>
                        <td>{{ item.production_Material_BusinessType }}</td>
                        <td>{{ item.business_status }}</td>
                        <td>{{ formatDate(item.audit_date) }}</td>
                        <td>
                            <button class="link-btn" @click="showDetail(item)">查看</button>
                            <button class="link-btn" @click="closeItem(item)">关闭</button>
                            <button class="link-btn danger" @click="deleteItem(item)">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </template>

        <!-- 分页 -->
        <div class="pagination">
            <span>共{{ searchParams.totalCount }}条</span>
            <select v-model="searchParams.PageSize" @change="handlePageSizeChange" class="page-select">
                <option value="10">10条/页</option>
                <option value="20">20条/页</option>
                <option value="50">50条/页</option>
                <option value="100">100条/页</option>
            </select>
            <div class="page-control">
                <button @click="prevPage" :disabled="searchParams.PageIndex <= 1">‹</button>
                <span>第 {{ searchParams.PageIndex }} 页</span>
                <button @click="nextPage" :disabled="searchParams.PageIndex >= searchParams.totalPage">›</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { utils, writeFile } from 'xlsx'
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const route = useRoute();

const isDetail = ref(false)
const tableData = ref([])
const detailTableData = ref([])
const isAllChecked = ref(false)

const searchParams = reactive({
    ProcessGId: '',
    ProcessSid: '',
    ProcessBId: '',
    ProcessWname: '',
    KTime: '',
    JTime: '',
    ProcessId: '',
    ProcessState: '',
    Processtype: '',
    ProcessDTime: '',
    PageIndex: 1,
    PageSize: 15,
    totalPage: 0,
    totalCount: 0,
})

const totalPages = computed(() => Math.ceil(searchParams.totalCount / searchParams.PageSize))

const filterData = (data, isDocument) => {
    if (!Array.isArray(data)) {
        console.error('传入 filterData 的 data 不是数组:', data);
        return [];
    }
    return data.filter(item => {
        const itemDate = dayjs(item.processTime);
        const startValid = !searchParams.KTime || itemDate.isSameOrAfter(dayjs(searchParams.KTime));
        const endValid = !searchParams.JTime || itemDate.isSameOrBefore(dayjs(searchParams.JTime));

        if (!startValid || !endValid) return false;

        if (isDocument) {
            return [
                item.processId.includes(searchParams.ProcessId),
                searchParams.ProcessState ? item.processState === searchParams.ProcessState : true,
                searchParams.Processtype ? item.processtype === searchParams.Processtype : true
            ].every(Boolean);
        } else {
            return [
                item.processGId.includes(searchParams.ProcessGId),
                item.processSid.includes(searchParams.ProcessSid),
                item.processWname.includes(searchParams.ProcessWname)
            ].every(Boolean);
        }
    });
}

const loadData = () => {
    try {
        const isDocumentView = isDetail.value;
        const sourceData = isDocumentView ? staticDocumentData.value : staticProductionData.value;
        const filteredData = filterData(sourceData, isDocumentView);

        const start = (searchParams.PageIndex - 1) * searchParams.PageSize;
        const end = start + Number(searchParams.PageSize);
        const pagedData = filteredData.slice(start, end);

        if (isDocumentView) {
            detailTableData.value = pagedData.map(item => ({
                ...item,
                production_Material_Id: item.processId,
                production_Material_DocumentDate: item.processTime,
                production_Material_Status: item.processState,
                production_Material_BusinessType: item.processtype,
                business_status: item.processAsaste || '正常',
                audit_date: item.processDTime || '-',
                isChecked: false
            }));
        } else {
            tableData.value = pagedData.map(item => ({
                ...item,
                measure_number: item.processGId,
                measure_code: item.processId,
                batch_status: item.processState,
                production_number: item.processSid,
                material_name: item.processWname,
                material_code: item.processBId,
                main_unit: '-',
                production_item: item.processXType,
                process: item.processzhong,
                construction_qty: item.processNumber,
                quality: item.processattribute || '未定义',
                workers: item.processworker,
                unit_date: item.processTime
            }));
        }

        searchParams.totalCount = filteredData.length;
        searchParams.totalPage = Math.ceil(filteredData.length / searchParams.PageSize);
    } catch (error) {
        ElMessage.error('数据加载失败');
        console.error(error);
    }
}

const toggleDetail = () => {
    isDetail.value = !isDetail.value;
    searchParams.PageIndex = 1;
    loadData();
}

const handleSearch = () => {
    searchParams.PageIndex = 1;
    loadData();
}

const handlePageSizeChange = () => {
    searchParams.PageIndex = 1;
    loadData();
}

const prevPage = () => {
    if (searchParams.PageIndex > 1) {
        searchParams.PageIndex--;
        loadData();
    }
}

const nextPage = () => {
    if (searchParams.PageIndex < searchParams.totalPage) {
        searchParams.PageIndex++;
        loadData();
    }
}

const handleAllCheck = () => {
    detailTableData.value.forEach(item => item.isChecked = isAllChecked.value);
}

const handleSingleCheck = (item) => {
    isAllChecked.value = detailTableData.value.every(item => item.isChecked);
}

const formatDate = (date) => dayjs(date).format('YYYY-MM-DD');

const closeItem = (item) => {
    ElMessageBox.confirm('确定要关闭该单据吗？', '提示', { type: 'warning' })
        .then(() => {
            item.business_status = '系统关闭';
            ElMessage.success('关闭成功');
        })
        .catch(() => { })
}

const deleteItem = (item) => {
    ElMessageBox.confirm('确定删除该记录？', '警告', { type: 'error' })
        .then(() => {
            const sourceData = isDetail.value ? staticDocumentData.value : staticProductionData.value;
            const index = sourceData.findIndex(i => i.processId === item.processId);
            sourceData.splice(index, 1);
            loadData();
            ElMessage.success('删除成功');
        })
        .catch(() => { })
}

const handleDelete = () => {
    const selectedItems = detailTableData.value.filter(item => item.isChecked);
    if (selectedItems.length === 0) return ElMessage.warning('请选择要删除的项目');

    ElMessageBox.confirm(`确定删除${selectedItems.length}条记录？`, '警告', { type: 'error' })
        .then(() => {
            selectedItems.forEach(item => {
                const index = staticDocumentData.value.findIndex(i => i.processId === item.processId);
                staticDocumentData.value.splice(index, 1);
            });
            loadData();
            ElMessage.success('批量删除成功');
        })
        .catch(() => { })
}

const handleExport = () => {
    try {
        const exportData = isDetail.value
            ? filterData(staticDocumentData.value, true)
            : filterData(staticProductionData.value, false);

        const mappedData = exportData.map(item => {
            if (isDetail.value) {
                return {
                    单据编码: item.processId,
                    单据日期: formatDate(item.processTime),
                    单据状态: item.processState,
                    业务类型: item.processtype,
                    业务状态: item.processAsaste || '正常',
                    审核日期: formatDate(item.processDTime) || '-'
                };
            } else {
                return {
                    措施编号: item.processGId,
                    措施编码: item.processId,
                    单批状态: item.processState,
                    生产编号: item.processSid,
                    物料名称: item.processWname,
                    物料编码: item.processBId,
                    主计量: '-',
                    生产项: item.processXType,
                    工序: item.processzhong,
                    施工数量: item.processNumber,
                    质量: item.processattribute || '未定义',
                    工人: item.processworker,
                    单位日期: formatDate(item.processTime)
                };
            }
        });

        const worksheet = utils.json_to_sheet(mappedData);
        const workbook = utils.book_new();
        utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        const fileName = `${isDetail.value ? '生产单据' : '生产明细'}_${dayjs().format('YYYYMMDD_HHmmss')}.xlsx`;
        writeFile(workbook, fileName);

        ElMessage.success(`成功导出${exportData.length}条数据`);
    } catch (error) {
        ElMessage.error('导出失败: ' + error.message);
    }
}

const hoshow = () => {
    router.push("/ProcessReportFormAdd");
}

const staticDocumentData = ref([]);
const staticProductionData = ref([]);

const Dooks = () => {
    const params = {
        PageIndex: searchParams.PageIndex,
        PageSize: searchParams.PageSize,
        ProcessGId: searchParams.ProcessGId,
        ProcessSid: searchParams.ProcessSid,
        ProcessBId: searchParams.ProcessBId,
        ProcessWname: searchParams.ProcessWname,
        KTime: searchParams.KTime,
        ProcessId: searchParams.ProcessId,
        ProcessState: searchParams.ProcessState,
        Processtype: searchParams.Processtype,
        ProcessDTime: searchParams.ProcessDTime,
    };
    console.log('请求参数:', params);
    axios.get("https://localhost:7006/api/Process/ProcessShiw", {
        params
    })
        .then((res) => {
            console.log(res.data.data);
            if (Array.isArray(res.data.data.list)) {
                staticDocumentData.value = res.data.data.list;
                staticProductionData.value = res.data.data.list;
                searchParams.totalPage = res.data.data.totalPage;
                searchParams.totalCount = res.data.data.totalCount;
                loadData();
            } else {
                ElMessage.error('API 返回的数据格式有误，list 不是数组');
                console.error('API 返回的数据格式有误:', res.data);
            }
        })
        .catch((error) => {
            ElMessage.error('数据加载失败，请检查网络或重试');
            console.error('API 请求出错:', error);
        });
};

const showDetail=(item)=>{
    router.push(`/ProcessReportFormUpdate?ProcessId=${item.processId}`)
}


onMounted(() => {
    Dooks();
});
</script>

<style scoped>
.container {
    padding: 20px;
    background: #f5f7fa;
}

.search-container {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 20px;
}

.search-input,
.search-select {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    flex: 1;
    min-width: 180px;
}

.date-range {
    display: flex;
    gap: 10px;
    align-items: center;
}

.search-button {
    padding: 8px 16px;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.action-buttons {
    margin-bottom: 20px;
}

.btn {
    padding: 8px 15px;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;
}

.btn-primary {
    background: #409eff;
    color: white;
}

.btn-success {
    background: #67c23a;
    color: white;
}

.btn-warning {
    background: #e6a23c;
    color: white;
}

.btn-danger {
    background: #f56c6c;
    color: white;
}

.btn-info {
    background: #909399;
    color: white;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    margin-bottom: 20px;
}

.data-table th,
.data-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #e8e8e8;
    text-align: left;
}

.data-table th {
    background: #fafafa;
    font-weight: 500;
}

.pagination {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 15px;
    background: white;
}

.page-control button {
    padding: 5px 10px;
    margin: 0 5px;
    border: 1px solid #ddd;
    background: #fff;
}

.link-btn {
    color: #409eff;
    cursor: pointer;
    background: none;
    border: none;
    padding: 0 5px;
}

.link-btn.danger {
    color: #f56c6c;
}

input[type="checkbox"] {
    transform: scale(1.2);
    margin-right: 5px;
}
</style>